package org.ly817.busCode.core.client;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.ly817.busCode.protocol.protobuf.BusCode;

import java.util.Arrays;

/**
 * @author LuoYu
 * @date 2019/02/20 10:46
 * <p>
 * Description:
 * 服务调用客户端
 * BusClient.call(Call.busCode("1001")).param(staffId).invoke();
 * BusClient.call(Call.service("staffService").dot("findStaff")).param(staffId).invoke();
 */
public class BusClient {

    private EventLoopGroup work;

    private ServerBootstrap bootstrap;

    private volatile Channel channel;

    private static final BusClient INSTANCE;

    private ThreadLocal<BusCode.busMsg> callMsg = new ThreadLocal<BusCode.busMsg>();

    /**
     * todo 启动netty客户端
     */
    private BusClient() {
        work = new NioEventLoopGroup();
        bootstrap.group(work).channel(NioServerSocketChannel.class);

    }

    // 单例调用构造方法初始化
    static {
        INSTANCE = new BusClient();
    }

    public static BusClient getInstance() {
        return INSTANCE;
    }

    /**
     * todo 获取单例客户端实例，并将busCode保存为work线程私有
     * 使用者在这个基础上继续构建rpc调用的请求参数
     * Call工具类根据不同的调用方式构建成busMsg
     * @param busMsg
     */
    public static BusClient call(BusCode.busMsg busMsg){
        getInstance().callMsg.set(busMsg);
        return getInstance();
    }

    /**
     * 继续组装ThreadLocal中已经初始化的BusCode.busMsg
     * @param params
     */
    public BusClient param(Object... params){
        BusCode.busMsg msg = getInstance().callMsg.get();
        msg = msg.toBuilder().setPayLoad(Arrays.toString(params)).build();

        getInstance().callMsg.set(msg);
        return getInstance();
    }

    /**
     * 将组装好的busMsg通过netty客户端发送给netty服务端，并返回响应
     *
     * 获取服务端连接channel，将
     *
     */
    public Object invoke(){
        System.out.println(this.callMsg.get().toString());
        getInstance().callMsg.remove();
        return null;
    }
}
